﻿using System;
using AutoTaskSchedule.Core.Enums;
using FluentScheduler;

namespace AutoTaskSchedule.Core.Infrastructure
{
    public class AutoTaskSchedule :  IAutoTaskSchedule
    {
        public delegate void StartTaskHandler();

        public delegate void StopTaskHandler();

        public void Execute()
        {
            try
            {
                Trigger(AutoTaskScheduleEvent.Start);
                Main();
            }
            catch
            {
                Trigger(AutoTaskScheduleEvent.Stop);
            }
        }

        public event StartTaskHandler StartTaskEvent;
        public event StartTaskHandler StopTaskEvent;

        /// <summary>
        /// 任务入口函数
        /// </summary>
        /// <returns></returns>
        public virtual void Main()
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 触发事件
        /// </summary>
        /// <param name="autoTaskScheduleEvent"></param>
        protected void Trigger(AutoTaskScheduleEvent autoTaskScheduleEvent)
        {
            switch (autoTaskScheduleEvent)
            {
                case AutoTaskScheduleEvent.Start:
                    if (StartTaskEvent != null) StartTaskEvent.Invoke();
                    break;

                case AutoTaskScheduleEvent.Stop:
                    if (StopTaskEvent != null) StopTaskEvent.Invoke();
                    break;
            }
        }
    }
}